<template>
    <FIModel v-if="visible" v-model="visible" width="500" title="注册" @close="closeClick(ruleFormRef)" @confirm="submitForm(ruleFormRef)">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="register"
          :rules="registerRules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
        <el-form-item label="用户账号" prop="loginName">
          <FIInput v-model="register.loginName" clearable />
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <FIInput v-model="register.userName" clearable />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input
            class="input_css"
            :type="isHide == true ? 'password' : 'text'"
            v-model="register.password"
            placeholder="登录密码">
            <template #prefix>
              <el-icon style="vertical-align: middle"><Lock /></el-icon>
            </template>
            <template #suffix>
              <el-icon style="vertical-align: middle">
                <Hide v-if="isHide" @click="isHide=false"/>
                <View v-else @click="isHide=true"/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="surePassword">
          <el-input
            class="input_css"
            :type="isSureHide == true ? 'password' : 'text'"
            v-model="register.surePassword"
            placeholder="确认密码">
            <template #prefix>
              <el-icon style="vertical-align: middle"><Lock /></el-icon>
            </template>
            <template #suffix>
              <el-icon style="vertical-align: middle">
                <Hide v-if="isSureHide" @click="isSureHide=false"/>
                <View v-else @click="isSureHide=true"/>
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="所属组织机构">
          <FICascader-tree @select-node="selectNode" id="deptId" :inputWidth="inputWidth"></FICascader-tree>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="register.gender">
            <el-radio value="1">男</el-radio>
            <el-radio value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <FIInput v-model="register.mobile" clearable />
        </el-form-item>
        <el-form-item label="电子邮件" prop="email">
          <FIInput v-model="register.email" clearable />
        </el-form-item>
        <el-form-item label="固定电话" prop="businessPhone">
          <FIInput v-model="register.businessPhone" clearable />
        </el-form-item>
        <el-form-item label="工号" prop="jobNo">
          <FIInput v-model="register.jobNo" clearable />
        </el-form-item>  
      </el-form>
      <template #footer>
          <slot name="footer">
            <div class="dialog-footer">
              <FIButton id="cancelRegist" border @click="closeClick(ruleFormRef)">取消</FIButton>
              <FIButton id="regist" border @click="submitForm(ruleFormRef)"> 确定 </FIButton>
            </div>
          </slot>
        </template>
    </FIModel>
</template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, computed, watch,toRaw } from 'vue'
  import type { ComponentSize, FormInstance } from 'element-plus'
import { Hide,View,Lock } from '@element-plus/icons-vue';
  import FIFormItem from '@/components/FIFormItem.vue'
  import FIInput from '@/components/FIInput.vue'
  import FIForm from '@/components/FIForm.vue'
  import FIModel from '@/components/FIModel.vue'
  import { apiRegist } from '@/api/user'
  import { apiRequestPost } from '@/api/globalApi.js'
  import { useMessage} from '@/hooks/message'
  import { useRoute } from 'vue-router'
  import { getCurrentInstance } from 'vue'
  const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
  const route = useRoute()
  const emits = defineEmits(['close','update:modelValue','get-list'])
  const props = defineProps({
  // 圆角大小
  modelValue: {
    type: Boolean,
    default: false,
  },
  
})
  const register = reactive({
    userName: '',
    password: '',
    loginName: '',
    mobile: '',
    gender: '1',
    email: '',
    businessPhone:'',
    jobNo:'',
    deptId:'',
    surePassword:'',
  })
  const isHide = ref(true)
  const isSureHide = ref(true)
  const ruleFormRef = ref<FormInstance>()
  let visible: any = computed({
    get() {
        return props.modelValue
    },
    set(val) {
      if (!ruleFormRef.value) return
      ruleFormRef.value.resetFields()
      emits('update:modelValue', val)
    },
    })
    const validatePhone = (rule, value, callback) => {
      const phonePattern = /^1[3-9]\d{9}$/; // 中国大陆手机号验证规则
      if (!value) {
        callback(new Error('请输入手机号'));
      } else if (!phonePattern.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
  const registerRules = reactive({
    loginName: [{ required: true, message: '此为必填项', trigger: 'blur' }],
    userName:[{ required: true, message: '此为必填项', trigger: 'blur' }],
    password:[{ required: true, message: '此为必填项', trigger: 'blur' }],
    mobile:[{ required: true,validator: validatePhone, trigger: 'blur' }],
    surePassword:[{ required: true, message: '此为必填项', trigger: 'blur' }],
    email:[
      {required: true,message: '此为必填项',trigger: 'blur',},
      {type: 'email',message: '请输入正确的email地址',trigger: ['blur', 'change'],}
    ]
  })
  
  const inputWidth = ref('340px')
 
  const closeClick = (formEl: FormInstance | undefined) =>{
    register.userName = '',
    register.password = '',
    register.loginName = '',
    register.mobile = '',
    register.gender = '1',
    register.email = '',
    register.businessPhone = '',
    register.jobNo = '',
    register.deptId = '',
    register.surePassword = '',
    emits('update:modelValue', false)
  }
  const selectNode = (val) =>{
    register.deptId = val
  }
  const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        const regex = /^[a-zA-Z0-9_]+$/;
        if (!regex.test(register.loginName)) {
          useMessage().warning('账号格式有误！请输入纯字母、纯数字，或者字母和下划线的组合！')
          return;
        }

        if(register.surePassword != register.password){
          useMessage().warning('两次输入密码不一致，请重新输入！')
          return;
        }
        
        const apiUrl = proxy.$Button_api('regist', route.name)
        apiRequestPost(apiUrl,toRaw(register))
          .then((res) => {
            if(res.data.success){
              useMessage().success(res.data.message)
              register.userName = '',
              register.password = '',
              register.loginName = '',
              register.mobile = '',
              register.gender = '1',
              register.email = '',
              register.businessPhone = '',
              register.jobNo = '',
              register.deptId = '',
              register.surePassword = '',
              emits('update:modelValue', false)
              emits('get-list')
            }
          })
          .catch((error: any) => {
            
          })
      }
    })
  }

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
  </script>
<style lang="less" scoped>
</style>
  